import React, { Component } from 'react';
import { NavigationEvents } from 'react-navigation';
import {
	StyleSheet, Text, View, TouchableOpacity, TextInput, Alert,
	Image, PixelRatio, FlatList, DeviceEventEmitter
} from "react-native";

import { API, API_GENERATE } from '../../../../config/api';
import HTTP from '../../../../utils/http';
import { GLOBAL } from '../../../../config/global';
import StorageHelper from '../../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../../config/storage';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common';
import ToastUtil from '../../../../utils/toast';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { ListItem } from '../../../enterprise/credit/judgement/_component/ListItem';
import { NewAccount } from '../../../../components/common/newAccount';
import { SlideSelect } from '../../../../components/common/slideSelect';
import { MDMCodeCpt } from '../../highSeas/_components/MDMCodeCpt';

const scale = GLOBAL.SCALE;

const searchIcon = require('../../../../imgs/global/whiteSearch.png');
const addIcon = require('../../../../imgs/customer/company-add.jpg');
const claimIcon = require('../../../../imgs/customer/renling.jpg');
const correct = require('../../../../imgs/global/correct.png');
const locked = require('../../../../imgs/customer/suoding.png');
const unLock = require('../../../../imgs/customer/zhengchang.png');
const TAB_LIST = [
	{
		name: '准入客户',
		key: 'passCnt',
		id: 0,
		count: 0,
		api: API.GET_CUSTOMER_LIST,
		isEdit: null,
		queryType: 'CRM_COMPANY'
	},
	{
		name: '草稿客户',
		key: 'editCnt',
		id: 1,
		count: 0,
		api: API.GET_CUSTOMER_APPLY_LIST,
		isEdit: '1',
		queryType: ''
	},
	{
		name: '审批中客户',
		key: 'approveCnt',
		id: 2,
		count: 0,
		api: API.GET_CUSTOMER_APPLY_LIST,
		isEdit: '2',
		queryType: ''
	}
]
export class CustomerIndexPage extends Component {
	constructor(props) {
		super(props);
		const { isLock, maintainFlag, choice } = this.props.navigation.state.params || {};
		this.state = {
			status: 'data',
			listData: [],
			refreshIcon: false, // 下拉刷新图标
			approveCntInfo: {},
			tabIndex: 0,
			isLock: isLock || 0,
			maintainFlag: maintainFlag || 0,
			alertShow: false,
			options: [],
			choice: choice || {}
		}

		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.totalPage = 1; // 总页数

		this.pageParams = { // TODO
			searchCode: '',
			isEdit: null,
			pageNo: 1,
			pageSize: 10,
			queryType: ''
		}
		that = this;
	}
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '客户列表',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.navigate('CrMtManage') }} color='#fff' />,
			headerRight: (
				<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', marginRight: 17 }}>
					<TouchableOpacity style={{ marginRight: 12 * scale }} activeOpacity={0.8}
						onPress={() => {
							navigation.navigate('EnterpriseCreateBaseInfo', {
								createNew: true,
								choice: that.state.choice
							});
						}}>
						<Image source={addIcon} style={{ width: 19, height: 19 }} />
					</TouchableOpacity>
				</View>
			),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center',
			},
			gesturesEnabled: false
		}
	};


	//初始化数据
	async componentDidMount() {
		await this.getSorage();
		await this.getRecord();
		await this.initPage();
		DeviceEventEmitter.addListener('refreshPage', (tabIndex) => {
			this.setState({
				tabIndex
			}, async () => {
				await this.getSorage();
				await this.getRecord();
				await this.initPage();
			})
		});
	}

	componentWillUnmount() {
		this.pageParams.pageNo = 1;
	}

	//获取业务组织
	async getSorage() {
		const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);

		const userInfo = JSON.parse(userInfoJson);
		this.corpId = userInfo.corpInfoTOs && userInfo.corpInfoTOs[0].corpId;
		this.setState({
			options: userInfo.corpInfoTOs || [],
			choice: this.state.choice.corpId ? this.state.choice : this.corpId
		})
	}

	async initPage() {
		let { maintainFlag, isLock } = this.state;
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		this.pageParams.isLock = isLock;//针对审批通过的接口
		this.pageParams.maintainFlag = maintainFlag;//针对准入客户的接口
		this.pageParams.queryType = TAB_LIST[this.state.tabIndex].queryType;//针对审批通过的接口
		this.pageParams.isEdit = TAB_LIST[this.state.tabIndex].isEdit;
		this.pageParams.corpId = this.state.choice.corpId || this.corpId;
		let res = await HTTP.POST(API_GENERATE(TAB_LIST[this.state.tabIndex].api), this.pageParams); // TODO
		if (res) {
			this.totalPage = res.totalPage;
			this.setState({
				status: res.rows && res.rows.length > 0 ? 'data' : 'empty',
				listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
				refreshIcon: false,
				curTypeCnt: res.recordCount || 0
			})
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error'
			})
		}
	}

	getRecord() {
		let { isLock, maintainFlag, choice } = this.state;
		TAB_LIST.map(async (item, index) => {
			let res = await HTTP.POST(API_GENERATE(item.api), {
				isEdit: item.isEdit,
				queryType: item.queryType,
				isLock,
				maintainFlag,
				corpId: this.state.choice.corpId || this.corpId
			})
			item.count = res.recordCount || 0;
		})

		this.setState({ TABLIST: TAB_LIST })
	}

	// 刷新页面 ifSearch--true刷新列表上数值,false不刷新。
	reloadPage(ifSearch) {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.initPage();
		this.getRecord();
		this.setState({ ifSearch })
	}

	// 下拉刷新
	refresh() {
		this.pageParams.pageNo = 1;
		this.reload = false;
		this.getRecord();
		this.initPage();
	}

	// 上拉翻页
	loadMore() {
		if (this.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}

	//切换状态
	changeTab(index) {
		if (this.state.tabIndex === index) return;
		this.pageParams.searchCode = '';
		this.setState({
			tabIndex: index
		}, () => {
			this.reloadPage();
		})
	}

	//点击锁定
	checkFrozen(objStr, value) {
		this.setState({
			[objStr]: !value ? 1 : 0
		}, () => {
			if (this.state.tabIndex) { return } else this.reloadPage(true);
		})
	}

	_delItem(applyId) {
		if (this.requesting) return;
		Alert.alert('提示', '确认删除这条记录？', [
			{ text: '取消' },
			{
				text: '确定', onPress: async () => {
					this.requesting = true;
					const response = await HTTP.POST(API_GENERATE(API.DEL_COMPANY_APPLY), { applyId });
					if (response) {
						this.requesting = false;
						ToastUtil.showSuccess('删除成功').then(() => {
							this.refresh();
						})
					} else {
						this.requesting = false;
					}
				}
			},
		]);
	}

	// 搜索View
	_renderFilterWrap() {
		const { isLock, maintainFlag } = this.state;
		return (
			<View style={styles.filterWrap}>
				<View>
					<Image source={searchIcon} style={styles.searchIcon} />
					<TextInput
						ref="enterpriseInput"
						style={styles.searchInput}
						underlineColorAndroid='transparent'
						placeholder={"请输入企业名称"}
						placeholderTextColor="rgba(255, 255, 255, .8)"
						maxLength={30}
						returnKeyType={'search'}
						defaultValue={this.pageParams.searchCode}
						onChangeText={(txt) => { this.pageParams.searchCode = txt; }}
						onSubmitEditing={() => { this.reloadPage(true); }}
					/>
				</View>
				<View>
					<TouchableOpacity activeOpacity={1} onPress={() => this.checkFrozen('isLock', isLock)} style={{ flexDirection: 'row', marginBottom: 15 * scale }}>
						<View style={styles.lockView} >
							{isLock ? <Image style={styles.lockImage} source={correct} /> : null}
						</View>
						<View><Text style={styles.lockText}>仅看锁定</Text></View>
					</TouchableOpacity>
					<TouchableOpacity activeOpacity={1} onPress={() => this.checkFrozen('maintainFlag', maintainFlag)} style={{ flexDirection: 'row' }}>
						<View style={styles.lockView} >
							{maintainFlag ? <Image style={styles.lockImage} source={correct} /> : null}
						</View>
						<View><Text style={styles.lockText}>超15天未跟进</Text></View>
					</TouchableOpacity>
				</View>

			</View>
		)
	}

	//tab View
	_renderTabWrap() {
		const { tabIndex, curTypeCnt, ifSearch, TABLIST } = this.state;
		return (
			<View style={styles.tabWrap}>
				{
					TABLIST && TABLIST.length && TABLIST.map((item, index) => {
						const totalCnt = tabIndex == index && ifSearch ? curTypeCnt : item.count;
						return (
							<TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(index) }} key={index} style={styles.tabItem}>
								<View style={tabIndex == index ? { borderBottomWidth: 2 * scale, borderBottomColor: '#fff' } : null}><Text style={[styles.tabText, tabIndex == index ? { fontWeight: 'bold' } : { opacity: .8 }]}>{item.name}</Text></View>
								<Text style={[styles.tabText, styles.tabCount, tabIndex == index ? { fontWeight: 'bold' } : { opacity: .8 }]}>{totalCnt}</Text>
							</TouchableOpacity>
						)
					})
				}
			</View>
		)
	}

	_renderListItem = (data) => {
		const { tabIndex } = this.state;
		const { companyId, companyName, status, statusName, applyId, auditComments, id, isLock, crmOverdueList, mdmCode } = data.item;
		return (
			<TouchableOpacity style={styles.listItem} key={data.index} onPress={() => {
				const { navigate } = this.props.navigation;
				//草稿和审批中的驳回-->创建，其他的跳至详情
				const goPage = (this.state.tabIndex && status !== 'WAIT' && status !== 'CONFIRM') ? 'EnterpriseCreateBaseInfo' : 'EnterpriseDetailsPage';
				console.log('goPage', goPage, this.companyIndex)
				navigate(goPage, {
					companyId,
					id,
					title: companyName,
					status: this.state.tabIndex ? 0 : 1, //审批通过可编辑，审批中不可编辑
					choice: this.state.choice,
					companyIndex: this.companyIndex || 0
				});
			}}>
				<View style={styles.listItemInfo}>
					<View style={styles.MDMCodeCpt}>
						{!mdmCode ? <MDMCodeCpt /> : null}
						<Text style={[styles.companyNameText, !mdmCode ? styles.opacity5 : null]}>{companyName.length > 14 ? `${companyName.substring(0, 14)}...` : companyName}</Text>
					</View>
					<TouchableOpacity style={styles.listItemRightInfo} activeOpacity={1}>
						{!tabIndex ? <Image source={isLock ? locked : unLock} style={{ width: 15 * scale, height: 15 * scale }} /> : null}
						{status == 'UNPASS' ?
							<Text style={[styles.companyNameText, { color: style.color.themeColor, }]}
								onPress={() => Alert.alert(auditComments || '无')}>【原因】</Text>
							: null}
						{status == 'EDIT' || status == 'UNPASS' ?
							<Text style={[styles.companyNameText, { color: style.color.themeColor }]}
								onPress={() => this._delItem(applyId)}>删除</Text>
							: null}
						{tabIndex == 2 ? <Text style={styles.companyNameText}>{statusName || '-'}</Text> : null}
					</TouchableOpacity>
				</View>
				{
					!tabIndex && crmOverdueList && crmOverdueList.length ?
						<View style={styles.listItemTips}>
							{
								crmOverdueList.map((item, index) => {
									//展示未维护天数 overdueCode = 'maintain'
									let day = item.overdueCode == 'maintain' ? (item.overdueDay + '天') : '';
									let tip = day + item.taskName;
									return (<Text style={styles.tipsText} key={index}> {tip}{index == (crmOverdueList.length - 1) ? '' : ' | '}</Text>)
								})
							}
						</View> : null
				}
			</TouchableOpacity>
		)

	}

	render() {
		const { status, listData, refreshIcon, alertShow, choice, options } = this.state;
		return (
			<View style={styles.container}>
				{options.length > 1 ? <NewAccount fn={(val) => { this.setState({ alertShow: val }) }} choice={choice.corpName || ''} /> : null}
				{this._renderFilterWrap()}
				{this._renderTabWrap()}

				{
					status == 'data' ? (
						<View style={{ flex: 1, backgroundColor: '#FFF' }}>
							<FlatList
								data={listData}
								renderItem={this._renderListItem}
								refreshing={refreshIcon}
								onRefresh={() => { this.refresh() }}
								onEndReachedThreshold={0.1}
								onEndReached={() => { this.loadMore() }}
							/>
						</View>) : null
				}
				{
					status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={() => { this.reloadPage() }} />) : null
				}

				<SlideSelect alertShow={alertShow} options={options}
					select={(val) => {
						this.companyIndex = val.selectIndex;
						this.setState({
							choice: val || options[0], alertShow: false, companyIndex: val.selectIndex,
						}, () => {
							this.reloadPage();
						})
					}}
					unselect={() => {
						this.setState({ alertShow: false })
					}} />
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray
	},
	headBox: {
		backgroundColor: style.color.themeColor,
		height: 190 * scale,
		width: '100%'
	},
	outSearch: {
		height: 36 * scale,
		width: '100%',
		flexDirection: 'row',
		justifyContent: 'center',
	},
	nerSearch: {
		height: 36 * scale,
		flexDirection: 'row',
	},
	searchStyle: {
		width: 260 * scale,
		height: 36 * scale,
		backgroundColor: 'rgb(110,178,253)',
		borderRadius: 6 * scale,
		marginLeft: 0
	},
	searchLeftIconStyle: {
		marginLeft: 50 * scale,
		tintColor: '#fff',
	},
	headBody: {
		marginTop: 20 * scale
	},
	filterWrap: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: style.color.themeColor,
		paddingTop: 14 * scale,
		paddingBottom: 14 * scale,
	},
	searchInput: {
		height: 36 * scale,
		width: 220 * scale,
		paddingLeft: 60 * scale,
		paddingRight: 12 * scale,
		backgroundColor: 'rgba(255, 255, 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingVertical: 0,
		position: 'relative',
		borderRadius: 8 * scale,
		color: '#fff',
	},
	searchIcon: {
		width: 22 * scale,
		height: 22 * scale,
		position: 'absolute',
		left: 24 * scale,
		top: 8 * scale,
		zIndex: 9,
		opacity: 0.8,
	},
	tabWrap: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		paddingLeft: 18 * scale,
		paddingRight: 18 * scale,
	},
	tabText: {
		color: '#fff',
		fontSize: 12 * scale,
		paddingTop: 14 * scale,
		paddingBottom: 12 * scale,
		paddingLeft: 4 * scale,
	},
	tabItem: {
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
	},
	lockView: {
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		height: 14 * scale,
		width: 14 * scale,
		borderWidth: 1 * scale,
		borderColor: '#fff',
		marginLeft: 14 * scale,
		marginRight: 10 * scale,
	},
	lockText: {
		fontSize: 10 * scale,
		color: '#fff'
	},
	lockImage: {
		tintColor: '#fff',
		width: 10 * scale,
		height: 8 * scale
	},
	listItem: {
		borderBottomWidth: 1 * scale,
		borderBottomColor: '#D8D8D8',
		paddingTop: 22 * scale,
		paddingBottom: 8 * scale,
	},
	listItemInfo: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		marginLeft: 24 * scale,
		marginRight: 28 * scale,
		marginBottom: 14 * scale,
	},
	listItemRightInfo: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center'
	},
	listItemTips: {
		flexDirection: 'row',
		// justifyContent: 'space-between',
		alignItems: 'center',
		marginLeft: 24 * scale,
		marginRight: 28 * scale,
		marginBottom: 14 * scale,
	},
	companyNameText: {
		fontSize: 14 * scale,
		color: '#000',
		fontWeight: '700',
		marginLeft: 8 * scale
	},
	tipsText: {
		fontSize: 12 * scale,
		color: '#E02020',
	},
	MDMCodeCpt: {
		flexDirection: 'row',
		alignItems: 'center'
	},
	opacity5: {
		opacity: .5
	}
})